package com.nidu.demo.notify.gatewayimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.PageQuery;
import com.alibaba.cola.dto.PageResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nidu.demo.common.enums.BooleanEnum;
import com.nidu.demo.notify.convertor.NotifyMessageConvertor;
import com.nidu.demo.notify.gateway.NotifyMessageGateway;
import com.nidu.demo.notify.mapper.NotifyMessageMapper;
import com.nidu.demo.notify.mapper.dataobject.NotifyMessageDO;
import com.nidu.demo.notify.model.NotifyMessage;
import com.nidu.demo.notify.model.NotifyMessageCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 站内信消息网关实现
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class NotifyMessageGatewayImpl implements NotifyMessageGateway {

    private final NotifyMessageMapper mapper;
    private final NotifyMessageConvertor convertor;

    @Override
    public NotifyMessage create(NotifyMessage notifyMessage) {
        NotifyMessageDO notifyMessageDO = convertor.toDataObject(notifyMessage);
        mapper.insert(notifyMessageDO);
        return convertor.toDomainObject(notifyMessageDO);
    }

    @Override
    public NotifyMessage update(NotifyMessage notifyMessage) {
        NotifyMessageDO notifyMessageDO = convertor.toDataObject(notifyMessage);
        mapper.updateById(notifyMessageDO);
        return convertor.toDomainObject(notifyMessageDO);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        mapper.deleteByIds(ids);
    }

    @Override
    public NotifyMessage getById(Long id) {
        NotifyMessageDO notifyMessageDO = mapper.selectById(id);
        if (notifyMessageDO == null) {
            return null;
        }
        return convertor.toDomainObject(notifyMessageDO);
    }

    @Override
    public List<NotifyMessage> getByIds(Set<Long> ids) {
        LambdaQueryWrapper<NotifyMessageDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(NotifyMessageDO::getId, ids);
        List<NotifyMessageDO> notifyMessageDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(notifyMessageDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(notifyMessageDOS);
    }

    @Override
    public List<NotifyMessage> listByCondition(NotifyMessageCriteria criteria) {
        LambdaQueryWrapper<NotifyMessageDO> wrapper = buildQueryWrapper(criteria);
        List<NotifyMessageDO> notifyMessageDOS = mapper.selectList(wrapper);
        if (CollUtil.isEmpty(notifyMessageDOS)) {
            return new ArrayList<>();
        }
        return convertor.toDomainObjects(notifyMessageDOS);
    }

    @Override
    public PageResponse<NotifyMessage> pageByCondition(NotifyMessageCriteria criteria) {
        // 创建查询条件
        LambdaQueryWrapper<NotifyMessageDO> wrapper = buildQueryWrapper(criteria);

        // 创建分页对象
        Page<NotifyMessageDO> page = new Page<>(criteria.getPageIndex(), criteria.getPageSize());

        // 排序字段
        if (!StrUtil.isEmpty(criteria.getOrderBy())) {
            if (PageQuery.DESC.equals(criteria.getOrderDirection())) {
                page.addOrder(OrderItem.desc(criteria.getOrderBy()));
            } else {
                page.addOrder(OrderItem.asc(criteria.getOrderBy()));
            }
        }

        // 执行分页查询
        mapper.selectPage(page, wrapper);
        List<NotifyMessage> notifyMessages = convertor.toDomainObjects(page.getRecords());
        return PageResponse.of(notifyMessages, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }

    @Override
    public void updateReadStatus(Long id) {
        NotifyMessageDO messageDO = new NotifyMessageDO();
        messageDO.setId(id);
        messageDO.setReadStatus(BooleanEnum.TRUE.getValue());
        messageDO.setReadTime(LocalDateTime.now());
        mapper.updateById(messageDO);
    }

    private LambdaQueryWrapper<NotifyMessageDO> buildQueryWrapper(NotifyMessageCriteria criteria) {
        LambdaQueryWrapper<NotifyMessageDO> wrapper = new LambdaQueryWrapper<>();
        
        // 时间范围条件
        LocalDateTime[] createTime = criteria.getCreateTime();
        if (createTime != null) {
            if (createTime.length == 1 && createTime[0] != null) {
                wrapper.ge(NotifyMessageDO::getCreateTime, createTime[0]);
            } else if (createTime.length > 1 && createTime[0] != null && createTime[1] != null) {
                wrapper.between(NotifyMessageDO::getCreateTime, createTime[0], createTime[1]);
            }
        }
        
        // 阅读时间范围条件
        LocalDateTime[] readTime = criteria.getReadTime();
        if (readTime != null) {
            if (readTime.length == 1 && readTime[0] != null) {
                wrapper.ge(NotifyMessageDO::getReadTime, readTime[0]);
            } else if (readTime.length > 1 && readTime[0] != null && readTime[1] != null) {
                wrapper.between(NotifyMessageDO::getReadTime, readTime[0], readTime[1]);
            }
        }
        
        // 精确查询条件
        wrapper.in(criteria.getIds() != null, NotifyMessageDO::getId, criteria.getIds());
        wrapper.eq(criteria.getUserId() != null, NotifyMessageDO::getUserId, criteria.getUserId());
        wrapper.eq(criteria.getTemplateId() != null, NotifyMessageDO::getTemplateId, criteria.getTemplateId());
        wrapper.eq(criteria.getReadStatus() != null, NotifyMessageDO::getReadStatus, criteria.getReadStatus());
        
        // 模糊查询条件
        wrapper.like(!StrUtil.isEmpty(criteria.getTemplateCode()), NotifyMessageDO::getTemplateCode, criteria.getTemplateCode());
        
        return wrapper;
    }

}
